package com.ctshk.rpc.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.IsDefaultCode;
import com.ctshk.common.enums.IsDeletedCode;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.utils.Assert;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.system.dto.AreaDTO;
import com.ctshk.rpc.system.dto.AreaTreeListDTO;
import com.ctshk.rpc.system.service.ISysAreaService;
import com.ctshk.rpc.user.dto.PassengerDTO;
import com.ctshk.rpc.user.dto.UserReceivingAddressDTO;
import com.ctshk.rpc.user.dto.UserReceivingAddressListDTO;
import com.ctshk.rpc.user.entity.Passenger;
import com.ctshk.rpc.user.entity.UserReceivingAddress;
import com.ctshk.rpc.user.mapper.UserReceivingAddressMapper;
import com.ctshk.rpc.user.req.UserReceivingAddressPageReq;
import com.ctshk.rpc.user.req.UserReceivingAddressReq;
import com.ctshk.rpc.user.service.IUserReceivingAddressService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;

/**
 * <p>
 *  用户收货地址接口实现类
 * </p>
 *
 * @author 李新科
 * @date 2021/5/17 20:45
 */
@DubboService
public class UserReceivingAddressServiceImpl extends ServiceImpl<UserReceivingAddressMapper, UserReceivingAddress> implements IUserReceivingAddressService {

    @Autowired
    private UserReceivingAddressMapper userReceivingAddressMapper;

    @DubboReference
    private ISysAreaService sysAreaService;

    @Override
    public Result<PageResponse<UserReceivingAddressListDTO>> queryPage(UserReceivingAddressPageReq req) {
        Page<UserReceivingAddress> queryPage = new Page(req.getPageNo(), req.getPageSize());
        Page<UserReceivingAddress> page = userReceivingAddressMapper.selectPage(queryPage, new QueryWrapper<UserReceivingAddress>()
                .lambda().eq(UserReceivingAddress::getUserId, req.getUserId())
                .eq(req.getIsDefalutAddress() != null,UserReceivingAddress::getIsDefalutAddress, req.getIsDefalutAddress())
                .eq(UserReceivingAddress::getIsDeleted, IsDeletedCode.NO.getCode()));

        List<UserReceivingAddressListDTO> listDTOS = EntityUtil.copyList(page.getRecords(), UserReceivingAddressListDTO.class);
        PageResponse<UserReceivingAddressListDTO> result = new PageResponse<>(listDTOS,
                page.getCurrent() == 1, page.getTotal() <= (page.getCurrent() *
                page.getSize()), page.getTotal(), page.getCurrent(), page.getSize());
        return Result.success(result);
    }

    @Override
    public Result add(UserReceivingAddressReq req) {
        long id = SnowflakeIdWorker.nextId();
        LocalDateTime now = LocalDateTime.now();
        Long userId = req.getUserId();
        UserReceivingAddress entity = EntityUtil.copy(req, UserReceivingAddress.class);
        entity.setId(id);
        entity.setUserId(userId);
        entity.setCreateId(userId);
        entity.setGmtCreate(now);
        entity.setGmtModified(now);

        // 设置国家,省,市,区名称
        setLocationName(entity,req.getLocationId());


        if(IsDefaultCode.YES.getCode().equals(entity.getIsDefalutAddress())) {
            UserReceivingAddress update = new UserReceivingAddress();
            update.setIsDefalutAddress(IsDefaultCode.NO.getCode());
            userReceivingAddressMapper.update(update,new UpdateWrapper<UserReceivingAddress>()
                    .lambda().eq(UserReceivingAddress::getUserId, userId));
        } else {
            entity.setIsDefalutAddress(IsDefaultCode.NO.getCode());
        }
        entity.setIsDeleted(IsDeletedCode.NO.getCode());
        userReceivingAddressMapper.insert(entity);
        return Result.success();
    }

    private void setLocationName(UserReceivingAddress entity,Long locationId) {
        AreaDTO areaDTO = sysAreaService.queryByEsId(locationId);
        if(areaDTO != null) {
            Integer i = areaDTO.getLevel();
            String countryTraditional = areaDTO.getCountryTraditional();
            entity.setCountryName(countryTraditional);
            StringJoiner sj = new StringJoiner("");
            sj.add(countryTraditional);
            if(i > 1) {
                String provinceTraditional = areaDTO.getProvinceTraditional();
                entity.setProvinceName(provinceTraditional);
                sj.add(provinceTraditional);
            }
            if(i > 2) {
                String cityTraditional = areaDTO.getCityTraditional();
                entity.setCityName(cityTraditional);
                sj.add(cityTraditional);
            }
            if(i > 3) {
                String areaTraditional = areaDTO.getAreaTraditional();
                entity.setAreaName(areaTraditional);
                sj.add(areaTraditional);
            }

            entity.setRegion(sj.toString());
        }

    }

    @Override
    public Result delete(Long id, Long userId) {
        userReceivingAddressMapper.delete(new QueryWrapper<UserReceivingAddress>()
                .lambda().eq(UserReceivingAddress::getId, id)
                .eq(UserReceivingAddress::getCreateId, userId));
        return Result.success();
    }

    @Override
    public Result<UserReceivingAddressDTO> detail(Long id, Long userId) {
        UserReceivingAddress userReceivingAddress = userReceivingAddressMapper.selectOne(new QueryWrapper<UserReceivingAddress>()
                .lambda().eq(UserReceivingAddress::getId, id)
                .eq(UserReceivingAddress::getCreateId, userId)
                .eq(UserReceivingAddress::getIsDeleted, IsDeletedCode.NO.getCode()));

        UserReceivingAddressDTO entityDTO = EntityUtil.copy(userReceivingAddress,UserReceivingAddressDTO.class);
        return Result.success(entityDTO);
    }

    @Override
    public Result update(UserReceivingAddressReq req) {
        Assert.nonNull(req.getId(), SystemError.SYS_412);
        LocalDateTime now = LocalDateTime.now();
        Long userId = req.getUserId();
        UserReceivingAddress entity = EntityUtil.copy(req, UserReceivingAddress.class);
        entity.setModifiedId(userId);
        entity.setGmtModified(now);
        // 设置国家,省,市,区名称
        setLocationName(entity,req.getLocationId());
        if(IsDefaultCode.YES.getCode().equals(entity.getIsDefalutAddress())) {
            UserReceivingAddress update = new UserReceivingAddress();
            update.setIsDefalutAddress(IsDefaultCode.NO.getCode());
            userReceivingAddressMapper.update(update,new UpdateWrapper<UserReceivingAddress>()
                    .lambda().eq(UserReceivingAddress::getUserId, userId));
        }
        userReceivingAddressMapper.update(entity,new UpdateWrapper<UserReceivingAddress>()
                .lambda().eq(UserReceivingAddress::getId, req.getId())
        .eq(UserReceivingAddress::getUserId, userId));

        return Result.success();
    }

    @Override
    public Result setDefaultAddress(Long id, Long userId,Integer isDefault) {
        UserReceivingAddress entity = new UserReceivingAddress();
        entity.setIsDefalutAddress(IsDefaultCode.NO.getCode());
        if(isDefault == 1) {
            userReceivingAddressMapper.update(entity,new UpdateWrapper<UserReceivingAddress>()
                    .lambda().eq(UserReceivingAddress::getUserId, userId));
            entity.setIsDefalutAddress(IsDefaultCode.YES.getCode());
            userReceivingAddressMapper.update(entity,new UpdateWrapper<UserReceivingAddress>()
                    .lambda().eq(UserReceivingAddress::getId, id));
        } else {
            userReceivingAddressMapper.update(entity,new UpdateWrapper<UserReceivingAddress>()
                    .lambda().eq(UserReceivingAddress::getId, id));
        }

        return Result.success();
    }
}
